import WxCanvas from './wx-canvas';
import * as echarts from './echarts';

function wrapTouch(event) {
  for (let i = 0; i < event.touches.length; ++i) {
    const touch = event.touches[i];
    touch.offsetX = touch.x;
    touch.offsetY = touch.y;
  }
  return event;
}

Component({
  properties: {
    canvasId: {
      type: String,
      value: 'ec-canvas'
    },
    ec: {
      type: Object
    }
  },
  data: {
    ec: null
  },
  ready: function () {
    if (this.data.ec) {
      this.init();
    }
  },
  methods: {
    init: function (callback) {
      // 如果已经初始化过且有图表实例，直接返回
      if (this.chart) {
        console.log('图表已存在，跳过初始化')
        return this.chart
      }
      
      const version = wx.version.version.split('.').map(n => parseInt(n, 10));
      const isValid = version[0] > 1 || (version[0] === 1 && version[1] >= 9);
      if (!isValid) {
        console.error('微信基础库版本过低，需大于等于 1.9.0');
        return;
      }
      
      // 创建新的canvas上下文
      try {
        const ctx = wx.createCanvasContext(this.data.canvasId, this);
        const canvas = new WxCanvas(ctx, this.data.canvasId);
        
        // 确保canvas对象有所有需要的方法
        canvas.addEventListener = canvas.addEventListener || function() {};
        canvas.removeEventListener = canvas.removeEventListener || function() {};
        
        echarts.setCanvasCreator(() => {
          return canvas;
        });
        
        // 添加重试机制和错误处理
        const initChart = (retry = 0) => {
          if (retry > 2) { // 减少重试次数
            console.error('获取canvas尺寸失败，已重试2次');
            return;
          }
          
          // 使用新的选择器方式
          const query = wx.createSelectorQuery().in(this);
          query.select('.ec-canvas')
            .fields({ node: true, size: true, rect: true })
            .exec((res) => {
              if (!res || !res[0] || !res[0].width || !res[0].height) {
                console.warn(`获取canvas尺寸失败，正在重试(${retry + 1}/2)...`);
                setTimeout(() => initChart(retry + 1), 150 * (retry + 1)); // 减少延迟时间
                return;
              }
              
              const rect = res[0];
              console.log('成功获取canvas尺寸:', rect.width, rect.height);
              
              try {
                // 设置canvas的尺寸属性
                canvas.width = rect.width;
                canvas.height = rect.height;
                canvas.offsetWidth = rect.width;
                canvas.offsetHeight = rect.height;
                
                if (typeof callback === 'function') {
                  this.chart = callback(canvas, rect.width, rect.height);
                  
                  // 检查图表是否成功创建
                  if (!this.chart) {
                    console.error('图表创建失败，回调函数未返回图表实例');
                  }
                }
                else if (this.data.ec && typeof this.data.ec.onInit === 'function') {
                  this.chart = this.data.ec.onInit(canvas, rect.width, rect.height);
                  
                  // 检查图表是否成功创建
                  if (!this.chart) {
                    console.error('图表创建失败，onInit函数未返回图表实例');
                  }
                }
              } catch (error) {
                console.error('初始化图表失败:', error);
              }
            });
        };
        
        // 延迟一小段时间确保组件已渲染
        setTimeout(() => {
          initChart();
        }, 100); // 减少延迟时间
      } catch (error) {
        console.error('创建canvas上下文失败:', error);
      }
    },
    canvasToTempFilePath(opt) {
      const query = wx.createSelectorQuery().in(this);
      query.select('.ec-canvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node;
          opt.canvas = canvas;
          wx.canvasToTempFilePath(opt);
        });
    },
    touchStart(e) {
      if (this.chart && e.touches.length > 0) {
        const touch = e.touches[0];
        const handler = this.chart.getZr().handler;
        handler.dispatch('mousedown', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.dispatch('mousemove', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.processGesture(wrapTouch(e), 'start');
      }
    },
    touchMove(e) {
      if (this.chart && e.touches.length > 0) {
        const touch = e.touches[0];
        const handler = this.chart.getZr().handler;
        handler.dispatch('mousemove', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.processGesture(wrapTouch(e), 'change');
      }
    },
    touchEnd(e) {
      if (this.chart) {
        const touch = e.changedTouches ? e.changedTouches[0] : {};
        const handler = this.chart.getZr().handler;
        handler.dispatch('mouseup', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.dispatch('click', {
          zrX: touch.x,
          zrY: touch.y
        });
        handler.processGesture(wrapTouch(e), 'end');
      }
    }
  }
}); 